<template>
  <div class="login-wrap">
    <img :src="imgSrc" class="receive-bg" alt="" />
    <div class="ms-login">
      <div class="ms-title">{{ title }}</div>
      <el-form
        :model="param"
        :rules="rules"
        ref="login"
        label-width="0px"
        class="ms-content"
      >
        <el-form-item>
          <template>
            <el-select
              v-model="param.value"
              placeholder="请选择"
              style="width: 100%"
              @change="currentSelectValue"
            >
              <el-option
                v-for="item in param.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="param.username" placeholder="username" clearable>
            <el-button
              slot="prepend"
              disabled
              icon="el-icon-lx-people"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="password"
            v-model="param.password"
            clearable
          >
            <el-button
              slot="prepend"
              disabled
              icon="el-icon-lx-lock"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="verify">
          <el-input
            placeholder="请输入验证码"
            v-model="param.verify"
            clearable
            :style="{ 'margin-bottom': '0px', width: '145px' }"
            @keyup.native.enter="getLogin()"
          ></el-input>
          <el-checkbox
            v-model="rememberPsw"
            style="color: #000; margin-left: 20px;"
            >记住密码</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <label
            :style="{
              color: 'white',
              'font-weight': 'bold',
              'font-size': '20px',
            }"
          >
            <span
              :style="{
                'vertical-align': 'middle',
                display: 'inline-block',
                'margin-right': '10px',
              }"
              >验证码:</span
            >
            <img
              :src="baseUrl + '/captcha?uuid=' + param.uuid"
              :style="{
                width: '150px',
                height: '30px',
                'vertical-align': 'middle',
              }"
              alt=""
              @click="changeSrc"
              ref="img"
          /></label>
        </el-form-item>

        <div class="login-btn">
          <el-button type="primary" @click="getLogin()">登录</el-button>
        </div>
      </el-form>
    </div>

    <p class="bottom-tip">
      <!-- <img src="../../../assets/img/邦凝logo.svg" alt="" /> -->
      <span>
        <!-- 杭州邦凝生态环境建设发展有限公司 -->
        启迪城服(杭州)环境科技有限公司
      </span>
    </p>
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
import { v4 as uuidv4 } from "uuid";
// import Cookies from "js-cookie";

import { mapMutations } from "vuex";
// 暂未实现
// import * as keys from "@/api/config.js";
// import JSEncrypt from "jsencrypt";
// console.log(keys);
export default {
  data() {
    return {
      imgSrc: "",
      title: "",
      rememberPsw: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      param: {
        options: [
          {
            label: "简体中文",
            value: "zh-CN",
          },
          {
            label: "繁体中文",
            value: "zh-TW",
          },
          {
            label: "English",
            value: "en-US",
          },
        ],
        value: "简体中文",
        uuid: uuidv4(),
        a: "b",
        username: "",
        password: "",
        verify: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        verify: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  watch: {},
  created() {
    switch (location.hostname) {
      case "vue.bangning.vip":
        this.imgSrc = require("../../../assets/img/02@2x.png");
        this.title = "物联网设备管理系统";
        break;
      case "bm.bangning.vip":
        this.imgSrc = require("../../../assets/img/d第二@2x.png");
        this.title = "再生资源商城管理系统";
        break;
      case "bn.bangning.vip":
        this.imgSrc = require("../../../assets/img/回收商城app管理系统@2x.png");
        this.title = "垃圾分类数据管理平台";
        break;
      default:
        this.imgSrc = require("../../../assets/img/02@2x.png");
        this.title = "物联网设备管理系统";
        break;
    }
    //判断是否记住密码
    if (localStorage.getItem("rememberPsw") == "true") {
      this.rememberPsw = true;
      this.getCookie();
    }
  },
  mounted() {
    console.dir(this.$refs.img);
  },
  methods: {
    // 私钥解密 用于解密后端返回的对称密钥 得到明文密钥 然后用于加密 密码
    // 暂未实现
    decrypt() {
      // 采用私钥进行解密
      var decrypt = new JSEncrypt();
      decrypt.setPrivateKey(keys.priKey1);
      var uncrypted = decrypt.decrypt(encrypted); // 解encrypted是后端返回的密文的密钥
      console.log(uncrypted); // 得到16位的明文的密钥 然后用它加密 密码
      return "secretkey123"; // 假设获取到了随机16位数字
    },
    //公钥加密 一般用不上
    encrypt() {},
    ...mapMutations({
      setToken: "SET_TOKEN",
    }),
    changeSrc() {
      this.param.uuid = uuidv4();
    },
    // 国际化
    currentSelectValue(currentLang) {
      console.log(currentLang);
      localStorage.setItem("currentLang", currentLang);
    },
    //设置cookie
    setCookie(portId, psw, exdays) {
      // Encrypt，加密账号密码
      var cipherUserName = CryptoJS.AES.encrypt(
        portId + "",
        "secretkey123"
      ).toString();
      var cipherPsw = CryptoJS.AES.encrypt(psw + "", "secretkey123").toString();
      console.log(cipherUserName + "/" + cipherPsw); //打印一下看看有没有加密成功

      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie，为什么这里用了==，因为加密后的字符串也有个=号，影响下面getcookie的字符串切割，你也可以使用更炫酷的符号。
      window.document.cookie =
        "username" +
        "==" +
        cipherUserName +
        ";path=/;expires=" +
        exdate.toGMTString();
      window.document.cookie =
        "password" +
        "==" +
        cipherPsw +
        ";path=/;expires=" +
        exdate.toGMTString();
    },
    //读取cookie
    getCookie: function() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式请根据自己的代码更改
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("=="); //根据==切割
          console.log(arr2);
          //判断查找相对应的值
          if (arr2[0] == "username") {
            // Decrypt，将解密后的内容赋值给账号
            var bytes = CryptoJS.AES.decrypt(arr2[1], "secretkey123");
            console.log(bytes);
            this.param.username = bytes.toString(CryptoJS.enc.Utf8);
            console.log(this.param.username);
          } else if (arr2[0] == "password") {
            // Decrypt，将解密后的内容赋值给密码
            var bytes = CryptoJS.AES.decrypt(arr2[1], "secretkey123");
            this.param.password = bytes.toString(CryptoJS.enc.Utf8);
          }
        }
      }
    },
    //清除cookie
    clearCookie: function() {
      this.setCookie("", "", -1);
    },
    getLogin() {
      // 验证
      this.$refs.login.validate((valid) => {
        if (valid) {
          this.$axios
            .post("/login", {
              username: this.param.username,
              password: this.param.password,
              uuid: this.param.uuid,
              captcha: this.param.verify,
            })
            .then(({ data: res }) => {
              // console.log(res);
              if (res.code !== 0) {
                this.$message.error(res.msg);
                this.changeSrc();
                return;
              }
              if (this.rememberPsw == true) {
                this.setCookie(this.param.username, this.param.password, 30);
              } else {
                this.clearCookie();
              }

              //这里是因为要在created中判断，所以使用了localstorage比较简单，当然你也可以直接根据cookie的长度or其他骚操作来判断有没有记住密码。
              localStorage.setItem("rememberPsw", this.rememberPsw);

              this.$message.success("登录成功");
              // Cookies.set("token", res.data.token);
              localStorage.setItem("ms_username", this.param.username);
              this.setToken(res.data.token);
              // console.log(this.$route.query.redirect);
              let redirect = decodeURIComponent(
                this.$route.query.redirect || "/"
              );
              this.$router.push({
                path: redirect,
              });
            });
        } else {
          if (
            this.param.username.trim().length === 0 ||
            this.param.password.trim().length === 0
          ) {
            this.$message.error("请输入账号或密码不能为空");
            return false;
          } else if (this.param.verify.trim().length === 0) {
            this.$message.error("请输入验证码");
            return false;
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  /* background-image: url(../../../assets/img/login-bg.jpg); */
  background-image: url("../../../assets/img/矢量智能对象@2x.png");
  background-size: 100% 100%;
  .bottom-tip {
    padding: 0;
    margin: 0;
    position: fixed;
    bottom: 0;
    text-align: center;
    width: 100%;
    background: #1a1a58;
    height: 40px;
    line-height: 40px;
    img {
      vertical-align: middle;
      width: 40px;
      height: 20px;
    }
    span {
      vertical-align: middle;
      font-size: 14px;
      color: #fff;
      display: inline-block;
    }
    &::after {
      content: "";
      display: inline-block;
      width: 0;
      height: 100%;
      vertical-align: middle;
    }
  }
}
.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
}
.receive-bg {
  /* width: 475.5px;
  height: 485px; */
  width: 40%;
  height: 55%;
  position: absolute;
  left: 10%;
  top: 50%;
  transform: translate(0, -50%);
}
.ms-login {
  position: absolute;
  left: 75%;
  top: 50%;
  /* transform: translate(0, -50%); */
  width: 350px;

  margin: -190px 0 0 -175px;

  border-radius: 10px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}
.ms-content {
  padding: 30px 30px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}
</style>
